package kr.hyunist.musicplayexer.Service;

import java.io.IOException;

import kr.hyunist.musicplayexer.IMediaService;
import kr.hyunist.musicplayexer.ListMainActivity;
import kr.hyunist.musicplayexer.PlayDetail;
import kr.hyunist.musicplayexer.R;
import kr.hyunist.musicplayexer.Application.MediaApplication;
import kr.hyunist.musicplayexer.Util.Util;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MediaService extends Service {
	MediaApplication app; // 어플리케이션 객체
	Notification mNotification;
	NotificationManager mNotificationManager;
	Intent notiIntent_prev, notiIntent_playAndPause, notiIntent_next,
			notiIntent_exit, notiIntent_startActivity;
	PendingIntent content_prev, content_playAndPause, content_next,
			content_exit, content_startActivity;
	final String NOTIPREV = "prevBtn";
	final String NOTIPLAYPAUSE = "playPauseBtn";
	final String NOTINEXT = "nextBtn";
	final String NOTIEXIT = "exitBtn";
	final String NOTISTART = "startBtn";
	IntentFilter notificationIntentFilter;
	RemoteViews notiView;
	RemoteViews bigNotiView;
	static final int NOTIFICATION_ID = 0x1994;
	int playIndex;
	Bitmap notiAlbumArt;
	
	@Override
	public void onCreate() {
		super.onCreate();
		app = (MediaApplication) getApplication();
		Log.d(ListMainActivity.TAG, "서비스에 app : " + app);
		Log.d(ListMainActivity.TAG, "Service - OnCreate");
		Log.d(ListMainActivity.TAG, "Service - mPlayer : " + app.mPlayer);

		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);

		notiIntent_startActivity = getPackageManager().getLaunchIntentForPackage("kr.hyunist.musicplayexer");
		notiIntent_startActivity.setAction(Intent.ACTION_MAIN);
		notiIntent_startActivity.addCategory(Intent.CATEGORY_LAUNCHER);
		notiIntent_startActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		notiIntent_prev = new Intent(NOTIPREV);
		notiIntent_playAndPause = new Intent(NOTIPLAYPAUSE);
		notiIntent_next = new Intent(NOTINEXT);
		notiIntent_exit = new Intent(NOTIEXIT);

		content_startActivity = PendingIntent.getActivity(getApplicationContext(), 0, notiIntent_startActivity, PendingIntent.FLAG_UPDATE_CURRENT);
		content_prev = PendingIntent.getBroadcast(getApplicationContext(), 0, notiIntent_prev, PendingIntent.FLAG_UPDATE_CURRENT);
		content_playAndPause = PendingIntent.getBroadcast(getApplicationContext(), 0, notiIntent_playAndPause, PendingIntent.FLAG_UPDATE_CURRENT);
		content_next = PendingIntent.getBroadcast(getApplicationContext(), 0, notiIntent_next, PendingIntent.FLAG_UPDATE_CURRENT);
		content_exit = PendingIntent.getBroadcast(getApplicationContext(), 0, notiIntent_exit, PendingIntent.FLAG_UPDATE_CURRENT);

		if (notificationIntentFilter == null) {
			notificationIntentFilter = new IntentFilter();
			notificationIntentFilter.addAction(NOTIPREV);
			notificationIntentFilter.addAction(NOTIPLAYPAUSE);
			notificationIntentFilter.addAction(NOTINEXT);
			notificationIntentFilter.addAction(NOTIEXIT);
			notificationIntentFilter.addAction(NOTISTART);
			registerReceiver(mReceiver, notificationIntentFilter);
		}

		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.d(ListMainActivity.TAG, "Service - onBind : " + mBinder);
		return mBinder;
	}

	IMediaService.Stub mBinder = new IMediaService.Stub() {
		String path;
		
		@Override
		public void onListItemSelectplayBackMusic(int index) throws RemoteException {
			Intent playerIntent = new Intent("com.android.music.musicservicecommand");
			playerIntent.putExtra("command", "pause");
			getApplicationContext().sendBroadcast(playerIntent);
			
			app.setCurrentPosition(index);
			path = app.getArList().get(app.getCurrentPosition()).getData();

			try {
				if (app.mPlayer != null) {
					app.mPlayer.stop();
					app.mPlayer.release();
					app.mPlayer = null;
				}

				app.mPlayer = new MediaPlayer();
				app.mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				app.mPlayer.setDataSource(path);
				app.mPlayer.prepare();
				app.mPlayer.start();

				Log.d(ListMainActivity.TAG, "서비스에서 생성된 app.mPlayer의 값 : " + app.mPlayer);

				app.mPlayer.setOnCompletionListener(new OnCompletionListener() {
					public void onCompletion(MediaPlayer mPlayer) {
						try {
							//요기서 repeat설정 해줘야할듯
							app.mService.next();
							
							/*app.mListActivity.CurrentPositionPlayBack();
							app.pDetail.CurrentSongInfo();*/
						} catch (RemoteException e) {

						}
					}
				});

			} catch (IllegalArgumentException e) {
				ErrorToast("onListItemSelectplayBackMusic IllegalArgumentException");
			} catch (SecurityException e) {
				ErrorToast("onListItemSelectplayBackMusic SecurityException");
			} catch (IllegalStateException e) {
				ErrorToast("onListItemSelectplayBackMusic IllegalStateException");
			} catch (IOException e) {
				ErrorToast("onListItemSelectplayBackMusic IOException");
			}
			playerIntent.putExtra("command", "start");
			getApplicationContext().sendBroadcast(playerIntent);
			
			// 음악재생시 BR실행
			notiView = new RemoteViews(getPackageName(), R.layout.notification);
			notiView.setOnClickPendingIntent(R.id.notiImage, content_startActivity);
			notiView.setOnClickPendingIntent(R.id.notiPrev, content_prev);
			notiView.setOnClickPendingIntent(R.id.notiPlayPause, content_playAndPause);
			notiView.setOnClickPendingIntent(R.id.notiNext, content_next);
			notiView.setOnClickPendingIntent(R.id.notiExit, content_exit);
			notiView.setTextViewText(R.id.notiTitle, app.getArList().get(app.getCurrentPosition()).getMusicTitle());
			notiView.setTextViewText(R.id.notiSinger, app.getArList().get(app.getCurrentPosition()).getArtist());
			notiView.setImageViewResource(R.id.notiPrev, R.drawable.notificationprev_selector);
			notiView.setImageViewResource(R.id.notiNext, R.drawable.notificationnext_selector);
			notiView.setImageViewResource(R.id.notiExit, R.drawable.notificationexit_selector);
			
			bigNotiView = new RemoteViews(getPackageName(), R.layout.notification_big);
			bigNotiView.setOnClickPendingIntent(R.id.notiImage, content_startActivity);
			bigNotiView.setOnClickPendingIntent(R.id.notiPrev, content_prev);
			bigNotiView.setOnClickPendingIntent(R.id.notiPlayPause, content_playAndPause);
			bigNotiView.setOnClickPendingIntent(R.id.notiNext, content_next);
			bigNotiView.setOnClickPendingIntent(R.id.notiExit, content_exit);
			bigNotiView.setTextViewText(R.id.notiTitle, app.getArList().get(app.getCurrentPosition()).getMusicTitle());
			bigNotiView.setTextViewText(R.id.notiSinger, app.getArList().get(app.getCurrentPosition()).getArtist());
			bigNotiView.setImageViewResource(R.id.notiPrev, R.drawable.notificationprev_selector);
			bigNotiView.setImageViewResource(R.id.notiNext, R.drawable.notificationnext_selector);
			bigNotiView.setImageViewResource(R.id.notiExit, R.drawable.notificationexit_selector);
			
			notiAlbumArt = Util.getArtworkQuick(getApplicationContext(),
					Integer.parseInt((app.getArList().get(app.getCurrentPosition())
							.getAlbumID())), 200, 200);
			
			if(notiAlbumArt != null) {
				notiView.setImageViewBitmap(R.id.notiImage, notiAlbumArt);
				bigNotiView.setImageViewBitmap(R.id.notiImage, notiAlbumArt);
			} else {
				notiView.setImageViewResource(R.id.notiImage, R.drawable.noimage);
				bigNotiView.setImageViewResource(R.id.notiImage, R.drawable.noimage);
			}
			
			if(app.mPlayer != null) {
				if(app.mPlayer.isPlaying()) {
					notiView.setImageViewResource(R.id.notiPlayPause, R.drawable.notificationplay_selector);
					bigNotiView.setImageViewResource(R.id.notiPlayPause, R.drawable.notificationpause_selector);

				} else {
					notiView.setImageViewResource(R.id.notiPlayPause, R.drawable.notificationplay_selector);
					bigNotiView.setImageViewResource(R.id.notiPlayPause, R.drawable.notificationpause_selector);

				}
	    	}
			mNotification = new Notification.Builder(getApplicationContext())
			.setSmallIcon(R.drawable.noti_icon)
			.setContent(notiView)
			.setPriority(Notification.PRIORITY_MAX)
			.setOngoing(true)
			.build();
			mNotification.bigContentView = bigNotiView;
			
			mNotificationManager.notify(NOTIFICATION_ID, mNotification);
		}

		@Override
		public void playAndPause() throws RemoteException {
			if(app.mPlayer != null) {
				if(app.mPlayer.isPlaying()) {
					app.mPlayer.pause();
					notiView.setImageViewResource(R.id.notiPlayPause, R.drawable.notificationplay_selector);
					bigNotiView.setImageViewResource(R.id.notiPlayPause, R.drawable.notificationplay_selector);
					mNotificationManager.notify(NOTIFICATION_ID, mNotification);
					/*if(MP3PlayActivity.playAndPause != null) {
						MP3PlayActivity.playAndPause.setBackgroundResource(MP3Theme.theme_play);
					}
					if(MP3PlayListActivity.playAndPause != null) {
						MP3PlayListActivity.playAndPause.setBackgroundResource(MP3Theme.theme_play);
					}
					if(multipleControlViewPlayAndPause != null) {
						multipleControlViewPlayAndPause.setBackgroundResource(R.drawable.btn_play_selected_image);
					}*/

				} else {
					app.mPlayer.start();
					notiView.setImageViewResource(R.id.notiPlayPause, R.drawable.notificationpause_selector);
					bigNotiView.setImageViewResource(R.id.notiPlayPause, R.drawable.notificationpause_selector);
					mNotificationManager.notify(NOTIFICATION_ID, mNotification);
					/*if(MP3PlayActivity.playAndPause != null) {
						MP3PlayActivity.playAndPause.setBackgroundResource(MP3Theme.theme_pause);
					}
					if(MP3PlayListActivity.playAndPause != null) {
						MP3PlayListActivity.playAndPause.setBackgroundResource(MP3Theme.theme_pause);
					}
					if(multipleControlViewPlayAndPause != null) {
						multipleControlViewPlayAndPause.setBackgroundResource(R.drawable.btn_pause_selected_image);
					}*/

				}
	    	}
		}
		
		@Override
		public void prev() throws RemoteException {
			playIndex = app.getCurrentPosition();
			int randIndex;
			if(app.mPlayer != null) {
				if (app.isShuffle) {
					randIndex = (int) (Math.random() * app.getArList().size());
					if(playIndex == randIndex){
						playIndex--;
						if(playIndex < 0) {
							playIndex = app.getArList().size()-1;
						}
					} else {
						playIndex = randIndex;
					}
				} else {
					playIndex--;
					if(playIndex < 0) {
						playIndex = app.getArList().size()-1;
					}
					
				}
				onListItemSelectplayBackMusic(playIndex);
				
				Log.d(ListMainActivity.TAG, "이전 곡 눌렀을때 포지션 값의 변화 : " + playIndex);
			}
		}

		@Override
		public void next() throws RemoteException {
			playIndex = app.getCurrentPosition();
			int randIndex;
			if(app.mPlayer != null) {
				if (app.isShuffle) {
					randIndex = (int) (Math.random() * app.getArList().size());
					if(playIndex == randIndex){
						playIndex++;
						if(playIndex > app.getArList().size()-1) {
							playIndex = 0;
						}
					} else {
						playIndex = randIndex;
					}
				} else {
					playIndex++;
					if(playIndex > app.getArList().size()-1) {
						playIndex = 0;
					}
					
				}
				
				onListItemSelectplayBackMusic(playIndex);
				
				Log.d(ListMainActivity.TAG, "다음 곡 눌렀을때 포지션 값의 변화 : " + playIndex);
			}
		}

		@Override
		public void setRepeatMode(int repeatmode) throws RemoteException {
			switch (repeatmode) {
			case 0:

				break;
			case 1:
				//app.mPlayer.setLooping(true);
				break;
			case 2:
				//app.mService.next();
				break;
			}
		}

		@Override
		public boolean getRepeatMode() throws RemoteException {
			return true;
		}

		@Override
		public int getCurrentPosition() throws RemoteException {
			return app.mPlayer.getCurrentPosition();
		}

	};


	// 서비스에서 음악 실행 시 BR로 Notificaton
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction() == NOTIPREV) {
				try {
					app.mService.prev();
				} catch (RemoteException e) {
					
				}
			} else if (intent.getAction() == NOTIPLAYPAUSE) {
				try {
					app.mService.playAndPause();
				} catch (RemoteException e) {
					
				}
			} else if (intent.getAction() == NOTINEXT) {
				try {
					app.mService.next();
				} catch (RemoteException e) {
					
				}
			} else if (intent.getAction() == NOTIEXIT) {
				mNotificationManager.cancel(NOTIFICATION_ID);
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		}

	};

	// 에러처리 토스트
	protected void ErrorToast(String str) {
		Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(ListMainActivity.TAG, "Service - OnDestroy");
		if (app.mPlayer != null) {
			app.mPlayer.stop();
			app.mPlayer.release();
			app.mPlayer = null;
		}
		
		mNotificationManager.cancel(NOTIFICATION_ID);
		mReceiver = null;
		mNotification = null;
		mNotificationManager = null;
	}
}
